package com.hhkj.study.api.user.common.session;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.hhkj.study.api.user.model.res.ApiCustomerUserBaseRes;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.RRExceptionCodeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.login.api.ApiSessionConst;
import com.ruoyi.framework.login.api.ApiSessionHolder;
import com.ruoyi.framework.login.api.ApiSessionKeyFilter;
import com.ruoyi.framework.login.api.ApiSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ApiAccountSessionKeyFilter
 *
 * @author SERVER
 * @since 2024/3/29 14:40
 */
@Component
@Order(1)
public class ApiAccountSessionKeyFilter implements ApiSessionKeyFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    public String getModelUrl() {
        return null;
    }

    @Override
    public List<String> urlWhiteList() {
        // 可以做成配置中获取白名单列表
        return Lists.newArrayList("/api/index");
    }

    @Override
    public boolean filter(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sessionKey = request.getHeader(ApiSessionConst.SESSION_KEY);
        if (StrUtil.isBlank(sessionKey)) {
            throw new ServiceException(RRExceptionCodeEnum.API_TIME_OUT.getMessage(), RRExceptionCodeEnum.API_TIME_OUT.getCode());
        }
        Object sessionObj = redisCache.getCacheObject(sessionKey);
        //session过期
        if (sessionObj == null) {
            ApiSessionHolder.clear();
            throw new ServiceException(RRExceptionCodeEnum.API_TIME_OUT.getMessage(), RRExceptionCodeEnum.API_TIME_OUT.getCode());
            // return Boolean.FALSE;
        } else {
            //不过期就存入全链路跟踪中
            ApiSessionHolder.setSessionObj(sessionObj);
            //刷新session剩余时长
            redisCache.setCacheObject(sessionKey, sessionObj, ApiSessionConst.SESSION_TIME_OUT, TimeUnit.MINUTES);
        }
        return Boolean.TRUE;
    }
}
